package com.hyk.commonLib.common.adapter;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseAdapter<VH extends BaseViewHolder<?, ?>, ITEM> extends RecyclerView.Adapter<VH> implements IAdapter<ITEM> {
    protected ArrayList<ITEM> itemList = new ArrayList<>();
    protected OnItemClickListener<ITEM> onItemClickListener;

    public BaseAdapter<VH, ITEM> insertItemList(List<ITEM> itemList, int position) {
        this.itemList.addAll(position, itemList);
        notifyItemRangeInserted(position, itemList.size());
        return this;
    }

    public BaseAdapter<VH, ITEM> addItemList(List<ITEM> itemList) {
        insertItemList(itemList, this.itemList.size());
        return this;
    }

    public BaseAdapter<VH, ITEM> setItemList(List<ITEM> itemList) {
        this.itemList.clear();
        this.itemList.addAll(itemList);
        notifyDataSetChanged();
        return this;
    }

    public BaseAdapter<VH, ITEM> removeItem(int position) {
        this.itemList.remove(position);
        notifyItemRemoved(position);
        return this;
    }

    public ITEM getItem(int position) {
        return itemList.get(position);
    }

    @Override
    public List<ITEM> getDataList() {
        return itemList;
    }

    @Override
    public int getItemCount() {
        return itemList.size();
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        onBindViewHolder(holder, position, getItem(position));
    }

    @Override
    public void notifyItemClickEvent(int position) {
        if (onItemClickListener != null)
            onItemClickListener.onClick(position, getItemViewType(position), getItem(position));
    }

    public BaseAdapter<VH, ITEM> setOnItemClickListener(OnItemClickListener<ITEM> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
        return this;
    }

    public abstract void onBindViewHolder(@NonNull VH holder, int position, ITEM item);

    public interface OnItemClickListener<ITEM> {
        void onClick(int position, int viewType, ITEM item);
    }
}
